
/**
 * created by jsq on 2017/10/18
 */
import React from 'react';
import {connect} from 'react-redux';
import {messages} from "share/common";

import {
  Form,
  Input,
  InputNumber,
  Switch,
  Button,
  Icon,
  message,
  Select,
  Row,
  Col
} from 'antd'

import callbackSettingService from 'containers/setting/callback-setting/callback-setting.service';
import "styles/setting/callback-setting/create-api-callback-setting.scss";

const FormItem = Form.Item;
const Option = Select.Option;

class CreateApiCallbackSetting extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      callbackUrlHelp: "",
      callbackUrlStatus: "",
      apiId: 0,
      apiCodeArray: [],
      firstRender: true,
      callbackUrl: {
        selectBefore: "Http://",
        selectAfter: ""
      },
      api: {
        isEnabled: true,
        callbackDatatype: 'json',
        jsq: 0, //1表示编辑，0表示新建
      },
    }
  }

  componentDidMount() {
    //这个参数传入，可以根据参数来判断是否是新增
    //为什么要    api.jsq = 1;来表示
    //点击回调设置的弹出新建的页面
    this.getApiCode();
    let api = Object.assign({}, this.props.params);
    api.isEnabled = this.props.params.isEnabled;
    api.callbackDatatype = 'json';
    api.jsq = 1;
    this.setState({
      apiId: this.props.params.id,
      api,
      loading: false,
    })
  }

  componentWillReceiveProps(nextProps) {
    if (JSON.stringify(nextProps.params) !== "{}") {
      if (this.state.firstRender) {
        //编辑
        if (nextProps.id) {
          let params = Object.assign({}, nextProps.params);
          params.jsq = 1;
          this.setState({
            api: params,
            firstRender: false,
            loading: false,
          })
        } else { //x新建
          this.getApiCode();
          let api = {
            callbackType: 'ASYNC',
            isEnabled: true,
            callbackDatatype: 'json',
            jsq: 0, //1表示编辑，0表示新建
          };
          this.props.form.setFieldsValue({callbackDatatype: "json"});
          this.setState({
            api,
            firstRender: false,
            loading: false,
          });
        }
      } else {
        this.setState({firstRender: true})
      }
    }
  }

  getApiCode() {
    let params = {
      page: 0,
      size: 1000
    }
    callbackSettingService.getApiCode(params)
      .then(response => {
        let apiCodeArray = [];
        response.data.map(item => {
          let option = {
            key: item.id,
            label: item.apiCode,
            version: item.apiVersion
          };
          apiCodeArray.push(option)
        });
        this.setState({apiCodeArray})
      })
  }

  //点击保存
  handleSubmit = (e) => {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      let callbackUrl = this.props.form.getFieldValue("callbackUrl");
      if (!callbackUrl) {
        this.setState({
          callbackUrlHelp: messages("common.please.enter"),
          callbackUrlStatus: "error"
        });
      }
      if (!err) {
        this.setState({loading: true});
        if (this.state.api.jsq === 1) {
          values.apiId = this.state.api.apiId;
          values.apiCode = this.state.api.apiCode;
          values.id = this.state.api.id;
          values.callbackUrl = values.callbackUrl;
          values.tenantId = this.props.company.tenantId;
          this.updateCallbackSetting(values);
        } else {
          if (this.state.api.id) {
            values.apiId = this.state.api.id;
          }
          values.tenantId = this.props.company.tenantId;
          this.addCallbackSetting(values);
        }
        values.companyOid = this.props.company.companyOID;
      }
    });
  };

  //新增
  addCallbackSetting = (values) => {
    callbackSettingService.addCallbackSetting(values)
      .then(response => {
        message.success(messages("common.operate.success"));
        this.props.form.resetFields();
        this.props.close();
      })
  }
  //编辑
  updateCallbackSetting = (values) => {
    callbackSettingService.validateCallback(values).then((response) => {
      if (response.status === 200) {
        if (response.data.code === "ERROR") {
          this.setState({
            loading: true,
            callbackUrlHelp: messages('setting.key166'/*校验失败！*/),
            callbackUrlStatus: "error"
          })
        } else {
          callbackSettingService.updateCallbackSetting(values)
            .then(response => {
              message.success(messages("common.operate.success"));
              this.props.form.resetFields();
              this.props.close();
            })
        }
      }
    })
  }

  onCancel = () => {
    this.props.form.resetFields();
    this.setState({
      callbackUrlHelp: "",
      callbackUrlStatus: "",
      api: {
        isEnabled: true
      },
      loading: false
    });
    this.props.close();
  };

  //获取22位随机字符串
  handleRandomString = () => {
    let charsArray = '1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM';
    let maxPos = charsArray.length;
    let string = '';
    for (let i = 0; i < 22; i++) {
      string += charsArray.charAt(Math.floor(Math.random() * maxPos));
    }
    this.props.form.setFieldsValue({"encodingAeskey": string});
    let api = this.state.api;
    api.companyOid = this.props.company.companyOid;
    api.isEnabled = this.props.form.getFieldValue("isEnabled");
    return string;
  };

  //校验地址是否可用
  handleValidateUrl = (e) => {
    if (typeof this.props.form.getFieldValue("callbackUrl") !== "undefined") {
      let params = {};
      let callbackDatatype = this.props.form.getFieldValue("callbackDatatype");
      params.callbackDatatype = 'json';
      params.encodingAeskey = typeof this.props.form.getFieldValue("encodingAeskey") === 'undefined' ? "" : this.props.form.getFieldValue("encodingAeskey");
      params.encodingToken = typeof this.props.form.getFieldValue("encodingToken") === 'undefined' ? "" : this.props.form.getFieldValue("encodingToken");
      params.callbackUrl = this.props.form.getFieldValue("callbackUrl");
      params.companyOid = this.props.company.companyOID;
      params.tenantId = this.props.company.tenantId;
      this.setState({
        callbackUrlHelp: params.callbackUrl === "" ? messages('common.please.enter') : "",
        callbackUrlStatus: params.callbackUrl === "" ? "error" : ""
      });
      if (params.callbackUrl !== "") {
        this.setState({loading: true});
        callbackSettingService.validateCallback(params).then((response) => {
          if (response.status === 200) {
            if (response.data.code === "ERROR") {
              this.setState({
                loading: true,
                callbackUrlHelp: messages('setting.key166'/*校验失败！*/),
                callbackUrlStatus: "error"
              })
            } else {
              this.setState({loading: false})
            }
          }
        }).catch((e) => {
          if (e.response) {
            message.error(`${messages('setting.key166'/*校验失败！*/)}, ${e.response.data.validationErrors[0].message}`);
          }
          this.setState({loading: false});
        })
      }

    }
  };

  //手动输入字符串
  handleInputString = (e) => {
    let value = e.target.value;
    if (value.length !== 22) {
      message.warning("encodingAeskey" + messages('setting.key167'/*需要22位*/))
    }
  };

  handleSelectApiCode = (value, option) => {
    this.props.form.setFieldsValue({"apiVersion": option.props.version});
    let api = this.state.api;
    api.apiId = parseInt(option.props.label);

    api.companyOid = this.props.company.companyOID;
    this.setState({
      api: api,
      apiId: parseInt(option.props.label)
    });
  };
  //监听表单值
  handleChange = (e) => {
    if (this.state.loading) {
      this.setState({
        loading: false,
      })
    }
  };

  render() {
    const {getFieldDecorator} = this.props.form;
    const {
      loading,
      api,
      callbackUrlStatus,
      callbackUrlHelp,
      apiCodeArray,
    } = this.state;

    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 14, offset: 0},
    };

    return (
      <div className="new-budget-control-rules-detail">
        <Form onSubmit={this.handleSubmit}
              onChange={this.handleChange}>
          <Row gutter={30}>
            <Col span={15} className="form-item-1">
              <FormItem {...formItemLayout}
                        label={messages('common.column.status')}>
                {getFieldDecorator('isEnabled', {
                  initialValue: api.isEnabled,
                  valuePropName: 'checked'
                })(
                  <Switch checkedChildren={<Icon type="check"/>}
                          unCheckedChildren={<Icon type="cross"/>}
                          onChange={(value) => {
                            api.isEnabled = value;
                            this.setState({api})
                          }}
                  />
                )}
              </FormItem>
            </Col>
            <Col span={4}>
              <span
                className="enabled-type">{api.isEnabled ?
                messages('common.status.enable') : messages('common.status.disable')}</span>
            </Col>
          </Row>
          <FormItem {...formItemLayout} label="API_CODE">
            {getFieldDecorator('apiId', {
              rules: [{
                required: true,
                message: messages('common.please.enter')
              },
              ],
              initialValue: api.apiCode
            })(
              <Select disabled={typeof api.id === 'undefined' ? false : true}
                      onSelect={this.handleSelectApiCode}
                      placeholder={messages('common.please.select')}>
                {apiCodeArray.map(item => <Option version={item.version} key={item.key}>{item.label}</Option>)}
              </Select>
            )}
          </FormItem>
          <Row gutter={30}>
            <Col span={24}>
              <FormItem {...formItemLayout} label="encodingAeskey">
                {getFieldDecorator('encodingAeskey', {
                  initialValue: api.encodingAeskey
                })(
                  <Input onBlur={this.handleInputString} className="call-back-setting-input"
                         placeholder={messages('common.please.enter')}/>
                )}
              </FormItem>
            </Col>
            <Col>
              <Button onClick={this.handleRandomString}
                      className="call-back-setting-btn">{messages('setting.key168'/*自动生成*/)}</Button>
            </Col>
          </Row>
          <FormItem {...formItemLayout} label="encodingToken">
            {getFieldDecorator('encodingToken', {
              initialValue: api.encodingToken
            })(
              <Input placeholder={messages('common.please.enter')}/> /*请输入*/
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('setting.key150'/*回调地址*/)}
                    help={callbackUrlHelp}
                    validateStatus={callbackUrlStatus}>
            {getFieldDecorator('callbackUrl', {
              initialValue: api.callbackUrl,
              rules: [
                {
                  required: true,
                  message: messages('common.please.enter')
                },
              ],
            })(
              <Input onBlur={this.handleValidateUrl} placeholder={messages('common.please.enter')}/>
            )}
          </FormItem> {/*回调类型*/}
          <FormItem {...formItemLayout} label={messages('setting.key169'/*回调类型*/)}>
            {getFieldDecorator('callbackType', {
              initialValue: api.callbackType
            })(
              <Select placeholder={messages('common.please.select')}>
                <options key="SYNC">{messages('setting.key170'/*同步*/)}</options>
                <options key="ASYNC">{messages('setting.key171'/*异步*/)}</options>
              </Select>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('setting.key152'/*数据格式*/)}>
            {getFieldDecorator('callbackDatatype', {
              initialValue: 'json'
            })(
              <Input disabled/>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('setting.key153'/*系统名称*/)}>
            {getFieldDecorator('sysName', {
              initialValue: api.sysName
            })(
              <Input placeholder={messages('common.please.enter')}/> /*请输入*/
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('setting.key154'/*管理员名称*/)}>
            {getFieldDecorator('sysAdmin', {
              initialValue: api.sysAdmin
            })(
              <Input placeholder={messages('common.please.enter')}/> /*请输入*/
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('setting.key155'/*管理员电话*/)}>
            {getFieldDecorator('sysAdminTel', {
              initialValue: api.sysAdminTel
            })(
              <Input placeholder={messages('common.please.enter')}/> /*请输入*/
            )}
          </FormItem>
          <FormItem {...formItemLayout}
                    label={messages('setting.key158'/*获取超时时间*/)}>
            {getFieldDecorator('connectTimeout', {
              initialValue: typeof api.connectTimeout === 'undefined' ? 0 : api.connectTimeout
            })(
              <InputNumber
                min={0}
                formatter={value => `${value}ms`}
                parser={value => value.replace('ms', '')}
                placeholder={messages('common.please.enter')}/> /*请输入*/
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('setting.key157'/*获取超链接时间*/)}>
            {getFieldDecorator('connectionRequestTimeout', {
              initialValue: typeof api.connectionRequestTimeout === 'undefined' ? 0 : api.connectionRequestTimeout
            })(
              <InputNumber
                min={0}
                formatter={value => `${value}ms`}
                parser={value => value.replace('ms', '')}
                placeholder={messages('common.please.enter')}/> /*请输入*/
            )}
          </FormItem>
          <div className="slide-footer">
            <Button type="primary" loading={loading} htmlType="submit">
              {messages('common.save')}
            </Button>
            <Button onClick={this.onCancel}>
              {messages('common.cancel')}
            </Button>
          </div>
        </Form>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    company: state.login.company
  }
}

const WrappedCreateApiCallbackSetting = Form.create()(CreateApiCallbackSetting);
export default connect(mapStateToProps)(WrappedCreateApiCallbackSetting);

/*
 "id": 1,
 "apiID": 1,
 //"api_code":"api_code",
 //"api_version":"api_version",
 "callbackUrl": "",
 "callbackDatatype": "",
 "sysName": "",
 "sysAdmin": "",
 "sysAdminTel": "",
 "connectTimeout": 0,
 "connectionRequestTimeout": 0,
 "sysinfo_hide": false
 */
